layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
});
layui.use(['utilObj', 'form', 'layer', 'laydate', 'table', 'laytpl', 'laypage', 'util'], function () {
    var utilObj = layui.utilObj;//自定义模块，包含ajax
    var laypage = layui.laypage;
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;
    var country = layer.pca;
    var getStorePageUrl = "cms/store/getStorePage";
    var storeDetailUrl = "cms/store/getStoreInfo";
    var validStoreUrl = "cms/store/validStore";
    var invalidStoreUrl = "cms/store/invalidStore";
    var storePage = {
        getData: function (pageIndex) {
            var storeName = $("input[name='storename']").val();
            var storeType = $("select[name='storeType']").val();
            var country = $("select[name='country']").val();
            var city = $("select[name='city']").val();
            var status = $("select[name='status']").val();

            var _jsonFilter = "{";
            if (storeName.length > 0) {
                _jsonFilter += "search_LIKE_name:'" + storeName + "',";
            }
            if (storeType.length > 0) {
                _jsonFilter += "search_EQ_type:'" + storeType + "',";
            }
            if (country.length > 0) {
                _jsonFilter += "search_EQ_country__id:'" + country + "',";
            }
            if (city.length > 0) {
                _jsonFilter += "search_EQ_city__id:'" + city + "',";
            }
            if (status.length > 0) {
                _jsonFilter += "search_EQ_isvalid:'" + status + "',";
            }
            if (_jsonFilter != "{") {
                _jsonFilter = _jsonFilter.substring(0, _jsonFilter.length - 1);
                _jsonFilter += "}";
            } else {
                _jsonFilter += "}";
            }
            utilObj.showLoading();
            utilObj.ajax({
                url: getStorePageUrl,
                data: {
                    jsonFilter: _jsonFilter,
                    pageSize: utilObj.pageSize,
                    pageIndex: pageIndex - 1
                },
                success: function (data) {
                    if (data && data.content) {
                        console.log(data);
                        storePage.tableIns = table.render({
                            elem: '#store-list',
                            cellMinWidth: 95,
                            page: false,
                            limit: utilObj.pageSize,
                            height: "full-225",
                            id: "storeListTable",
                            cols: [[
                                {
                                    field: 'name',
                                    title: '店铺名称',
                                    align: "center",
                                    width: 300
                                },
                                {
                                    field: 'type',
                                    title: '店铺类型',
                                    align: 'center',
                                    width: 120,
                                    templet: function (d) {
                                        if (d.type == 1) {
                                            return "专卖店";
                                        } else if (d.type == 2) {
                                            return "授权经销商";
                                        } else if (d.type == 3) {
                                            return "临时展台";
                                        }
                                    }
                                },
                                {
                                    field: 'country',
                                    title: '国家',
                                    align: 'center',
                                    width: 120,
                                    templet: function (d) {
                                        // return d.country.name;
                                        return d.country ? d.country.name : "";
                                    }
                                },
                                {
                                    field: 'city',
                                    title: '城市',
                                    align: 'center',
                                    width: 120,
                                    templet: function (d) {
                                        return d.city ? d.city.name : "";
                                    }
                                },
                                {
                                    field: 'contact',
                                    title: '店铺联系人',
                                    align: 'center',
                                    width: 120
                                },
                                {
                                    field: 'phone',
                                    title: '店铺联系电话',
                                    align: 'center',
                                    width: 250,
                                    templet: function (d) {
                                        return (d.contactNumber || "") + (d.contactNumber ? "-" : "") + (d.phone == "NULL" ? "" : d.phone || "");
                                    }
                                },
                                {
                                    field: 'address',
                                    title: '店铺地址',
                                    align: 'center',
                                    width: 350
                                },
                                {
                                    field: 'isvalid',
                                    title: '状态',
                                    align: 'center',
                                    width: 100,
                                    templet: function (d) {
                                        if (d.isvalid) {
                                            return "启用";
                                        } else {
                                            return "禁用";
                                        }
                                    }
                                },
                                {
                                    title: '操作',
                                    width: 170,
                                    fixed: "right",
                                    align: "center",
                                    templet: function (d) {
                                        var result = "<a class=\"layui-btn layui-btn-xs \" id=\"btn-detail\" lay-event=\"detail\">查看</a>";
                                        if (utilObj.getUser().role == 1) {
                                            result += "<a class=\"layui-btn layui-btn-xs\" id=\"btn-edit\" lay-event=\"edit\">编辑</a>";
                                            if (d.isvalid == 1) {
                                                result += "<a class=\"layui-btn layui-btn-xs layui-btn-warm\" id=\"btn-disabled\" lay-event=\"disabled\">禁用</a>";
                                            } else if (d.isvalid == 0) {
                                                result += "<a class=\"layui-btn layui-btn-xs layui-btn-warm\" id=\"btn-enabled\" lay-event=\"enabled\">启用</a>";
                                            }
                                        }
                                        return result;
                                    }
                                }
                            ]],
                            data: data.content
                        });
                        laypage.render({
                            elem: 'storePagination',
                            curr: pageIndex,
                            count: data.totalElements,
                            limit: utilObj.pageSize,
                            jump: function (obj, first) {
                                storePage.current = obj.curr;
                                if (!first) {
                                    storePage.getData(obj.curr);
                                }
                            }
                        });
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                }
            });
        },
        getStoreDetail: function (storeId, operator) {
            utilObj.showLoading();
            utilObj.ajax({
                url: storeDetailUrl,
                data: {
                    storeId: storeId
                },
                success: function (data) {
                    if (data) {
                        if (operator === 0) {
                            openStoreDetail(data);
                        } else if (operator === 1) {
                            editStoreDetail(data);
                        }
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                }
            });
        },
        changeStoreState: function (userId, storeId, requestUrl) {
            var requestData = {
                userId: userId,
                storeId: storeId
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: requestUrl,
                data: requestData,
                success: function (data) {
                    if (data) {
                        storePage.getData(storePage.current);
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                }
            });
        },
        initCountryCity: function () {
            //城市联动
//          for (var obj in layer.cityList) {
//              $("[name='country']").append(`<option value="${obj}">${layer.cityList[obj].name}</option>`);
//          }
            for (var obj of layer.cityList2) {
                $("[name='country']").append(`<option value="${obj.id}">${obj.country}</option>`);
            }
            form.render('select', "country");
            form.on('select(select-country)', function (data) {
                storePage.currentCountry = data.value;
                $("[name='city']").html(`<option value="">请选择城市</option>`);
                for (var obj in layer.cityList[data.value]) {
                    if (layer.cityList[data.value][obj].name)
                        $("[name='city']").append(`<option value="${obj}">${layer.cityList[data.value][obj].name}</option>`);
                }
                form.render('select', "city");
            });
        },
        init: function () {
            laydate.render({
                elem: '#startTime', type: 'date'
            });
            laydate.render({
                elem: '#endTime', type: 'date'
            });
            if (utilObj.getUser().role == 1) {
                $(".btn-addnew").show();
            } else {
                $(".btn-addnew").hide();
            }
            storePage.getData(1);
            storePage.initCountryCity();
            table.on('tool(store-list)', function (obj) {
                var layEvent = obj.event,
                    data = obj.data;
                if (layEvent === 'detail') {
                    storePage.getStoreDetail(data.id, 0);
                } else if (layEvent === 'edit') {
//                  if (data.isvalid) {
//                      layer.open({
//                          title: '提示',
//                          content: '请先禁用店铺再进行编辑'
//                      });
//                      return;
//                  } else {
//                  }
                    storePage.getStoreDetail(data.id, 1);
                } else if (layEvent === 'disabled') {
                    var usableText = "是否确定禁用此店铺？"
                    layer.confirm(usableText, {
                        icon: 3,
                        title: '系统提示',
                        cancel: function (index) {
                            layer.close(index);
                        }
                    }, function (index) {
                        layer.close(index);
                        var user = localStorage.getItem("user");
                        if (user) {
                            user = JSON.parse(user);
                            storePage.changeStoreState(user.userId, data.id, invalidStoreUrl);
                        }
                    }, function (index) {
                        layer.close(index);
                    });
                } else if (layEvent === 'enabled') {
                    var usableText = "是否确定启用此店铺？"
                    layer.confirm(usableText, {
                        icon: 3,
                        title: '系统提示',
                        cancel: function (index) {
                            layer.close(index);
                        }
                    }, function (index) {
                        layer.close(index);
                        var user = localStorage.getItem("user");
                        if (user) {
                            user = JSON.parse(user);
                            storePage.changeStoreState(user.userId, data.id, validStoreUrl);
                        }
                    }, function (index) {
                        layer.close(index);
                    });
                }
            });
        }
    };
    storePage.init();

    $(".btn_search").on('click', function () {
        storePage.getData(1);
    });

    $(".btn-addnew").on('click', function () {
        editStoreDetail();
    });


    function openStoreDetail(data) {
        if (data) {
            $(".storeId").val(data.id);
            var title = "店铺详情";
            var index = layui.layer.open({
                title: title,
                type: 2,
                content: "storeDetail.html",
                success: function (layero, index) {
                    var body = layui.layer.getChildFrame('body', index);
                    if (data) {
                        // store-id
                        body.find("#store-id").val(data.id);  //用户id
                        body.find(".storeName").text(data.name);
                        var storeType = "";
                        if (data.type == 1) {
                            storeType = "专卖店";
                        } else if (data.type == 2) {
                            storeType = "授权经销商";
                        } else if (data.type == 3) {
                            storeType = "临时展台";
                        }
                        body.find(".storeType").text(storeType);
                        if (data.type == 3) {
                            body.find(".storeTime").show();
                            body.find(".fromTime").text(data.startTime);
                            body.find(".toTime").text(data.endTime);
                        } else {
                            body.find(".storeTime").hide();
                        }
                        var canAppoint = data.canAppoint ? "可预约" : "不可预约";
                        body.find(".canAppoint").text(canAppoint);

                        if (data.salesList) {
                            var saleList = data.salesList.split(',');
                            for (var index in saleList) {
                                if (saleList[index] == 1) {
                                    body.find("input:checkbox[value='watch']").attr("checked", "checked").attr("disabled", "true");
                                } else if (saleList[index] == 2) {
                                    body.find("input:checkbox[value='jewelry']").attr("checked", "checked").attr("disabled", "true");
                                } else if (saleList[index] == 3) {
                                    body.find("input:checkbox[value='bag']").attr("checked", "checked").attr("disabled", "true");
                                } else if (saleList[index] == 4) {
                                    body.find("input:checkbox[value='perfume']").attr("checked", "checked").attr("disabled", "true");
                                } else if (saleList[index] == 5) {
                                    body.find("input:checkbox[value='glasses']").attr("checked", "checked").attr("disabled", "true");
                                }
                            }
                        }
                        body.find("input:checkbox[value='watch']").attr("disabled", "true");
                        body.find("input:checkbox[value='jewelry']").attr("disabled", "true");
                        body.find("input:checkbox[value='bag']").attr("disabled", "true");
                        body.find("input:checkbox[value='perfume']").attr("disabled", "true");
                        body.find("input:checkbox[value='glasses']").attr("disabled", "true");

                        body.find(".storeEnglishName").text(data.nameEn);
                        body.find(".storeContact").text(data.contact);
                        body.find(".contactNumber").text(data.contactNumber);
                        body.find(".storePhone").text(data.phone);

                        body.find("#sunday").text(data.opentimeSun);
                        body.find("#monday").text(data.opentimeMon);
                        body.find("#tuesday").text(data.opentimeTue);
                        body.find("#wednesday").text(data.opentimeWed);
                        body.find("#thursday").text(data.opentimeThu);
                        body.find("#friday").text(data.opentimeFri);
                        body.find("#saturday").text(data.opentimeSat);
                        var bannerContent = '';
                        for (var i = 1; i <= 5; i++) {
                            if (data['image' + i]) {
                                bannerContent += '<div img="' + d["image" + i] + '" class="table-cell-image" style="background-image:url(' + d["image" + i] + ')"></div>';
                            }
                        }
                        body.find("#store-banner").innerHeight = bannerContent;

                        body.find(".event-title").text(data.eventTitle);
                        body.find(".event-englishtitle").text(data.eventTitleEn);
                        body.find(".event-url").text(data.eventUrl);

                        body.find(".storeCountry").text(data.country);
                        body.find(".storeCity").text(data.city);
                        body.find(".storeAddress").text(data.address);
                        body.find(".storeEnglishAddress").text(data.addressEn);

                        var iframeWindow1 = layero.find('iframe')[0].contentWindow;
                        iframeWindow1.layui.form.render();
                    }
                }
            });
            layui.layer.full(index);
            window.sessionStorage.setItem("index", index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(window.sessionStorage.getItem("index"));
            })
        }
    }

    function editStoreDetail(data) {
        var title = "新增店铺";
        var params = "";
        if (data) {
            title = "编辑店铺";
            if (data.lat && data.lon) {
                params = "?lat=" + data.lat + "&lon=" + data.lon;
            }
        }
        var index = layui.layer.open({
            title: title,
            type: 2,
            content: "storeEdit.html" + params,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (data) {
                    // store-id
                    body.find("#store-id").val(data.id);
                    body.find(".storeName").val(data.name);
                    body.find(".storeEnglishName").val(data.nameEn);
                    body.find(".storeContact").val(data.contact);
                    body.find(".contactNumber").val(data.contactNumber);
                    body.find(".storePhone").val(data.phone);

                    if (data.salesList) {
                        var saleList = data.salesList.split(',');
                        for (var index in saleList) {
                            if (saleList[index] == 1) {
                                body.find("input:checkbox[value='watch']").attr("checked", "checked");
                            } else if (saleList[index] == 2) {
                                body.find("input:checkbox[value='jewelry']").attr("checked", "checked");
                            } else if (saleList[index] == 3) {
                                body.find("input:checkbox[value='bag']").attr("checked", "checked");
                            } else if (saleList[index] == 4) {
                                body.find("input:checkbox[value='perfume']").attr("checked", "checked");
                            } else if (saleList[index] == 5) {
                                body.find("input:checkbox[value='glasses']").attr("checked", "checked");
                            }
                        }
                    }
                    if (data.opentimeSun) {
                        var sunTime = data.opentimeSun.split('-');
                        body.find("#sunday-start").val(sunTime[0]);
                        body.find("#sunday-end").val(sunTime[1]);
                    }
                    if (data.opentimeMon) {
                        var monTime = data.opentimeMon.split('-');
                        body.find("#monday-start").val(monTime[0]);
                        body.find("#monday-end").val(monTime[1]);
                    }
                    if (data.opentimeTue) {
                        var tueTime = data.opentimeTue.split('-');
                        body.find("#tuesday-start").val(tueTime[0]);
                        body.find("#tuesday-end").val(tueTime[1]);
                    }
                    if (data.opentimeWed) {
                        var wedTime = data.opentimeWed.split('-');
                        body.find("#wednesday-start").val(wedTime[0]);
                        body.find("#wednesday-end").val(wedTime[1]);
                    }
                    if (data.opentimeThu) {
                        var thuTime = data.opentimeThu.split('-');
                        body.find("#thursday-start").val(thuTime[0]);
                        body.find("#thursday-end").val(thuTime[1]);
                    }
                    if (data.opentimeFri) {
                        var friTime = data.opentimeFri.split('-');
                        body.find("#friday-start").val(friTime[0]);
                        body.find("#friday-end").val(friTime[1]);
                    }
                    if (data.opentimeSat) {
                        var satTime = data.opentimeSat.split('-');
                        body.find("#saturday-start").val(satTime[0]);
                        body.find("#saturday-end").val(satTime[1]);
                    }
                    if (data.type == 3) {
                        body.find(".storeTime").show();
                        body.find(".fromTime").val(data.startTime);
                        body.find(".toTime").val(data.endTime);
                    } else {
                        body.find(".storeTime").hide();
                    }
                    body.find(".storeType").val(data.type);
                    var canAppoint = data.canAppoint ? "1" : "0";
                    body.find(".canAppoint").val(canAppoint);

                    var bannerContent = '';
                    for (var i = 1; i <= 5; i++) {
                        if (data['image' + i]) {
                            bannerContent += '<div img="' + d["image" + i] + '" class="table-cell-image" style="background-image:url(' + d["image" + i] + ')"></div>';
                        }
                    }
                    body.find("#store-banner").html(bannerContent);

                    body.find(".event-title").val(data.eventTitle);
                    body.find(".event-englishtitle").val(data.eventTitleEn);
                    body.find(".event-url").val(data.eventUrl);

                    body.find(".storeAddress").val(data.address);
                    body.find(".storeEnglishAddress").val(data.addressEn);

                    // 三联动
//                  for (var obj in layer.cityList) {
//                      body.find("[name='country']").append(`<option value="${obj}">${layer.cityList[obj].name}</option>`);
//                  }
                    for (var obj of layer.cityList2) {
                        body.find("[name='country']").append(`<option value="${obj.id}">${obj.country}</option>`);
                    }
                    for (var index in layer.cityList2) {
                        if (layer.cityList2[index].country
                            && layer.cityList2[index].country == data.country) {
                            var tempCityList = layer.cityList2[index].cityList;
                            for (var inIndex in tempCityList) {
                                body.find("[name='city']").append(`<option value="${tempCityList[inIndex].id}">${tempCityList[inIndex].cityName}</option>`);
                            }
                        }
                    }
                    for (var index in layer.cityList2) {
                        if (layer.cityList2[index].country == data.country) {
                            body.find("[name='country']").val(layer.cityList2[index].id);
                            var tempCityList = layer.cityList2[index].cityList;
                            for (var inIndex in tempCityList) {
                                if (tempCityList[inIndex].cityName && tempCityList[inIndex].cityName == data.city) {
                                    body.find("[name='city']").val(tempCityList[inIndex].id);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    var iframeWindow = layero.find('iframe')[0].contentWindow;
                    iframeWindow.layui.form.render();
                } else {
                    for (var obj in layer.cityList) {
                        body.find("[name='country']").append(`<option value="${obj}">${layer.cityList[obj].name}</option>`);
                    }
                    var iframeWindow = layero.find('iframe')[0].contentWindow;
                    iframeWindow.layui.form.render();
                }

            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index", index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }

    //是否置顶
    form.on('switch(newsTop)', function (data) {
        var index = layer.msg('修改中，请稍候', {icon: 16, time: false, shade: 0.8});
        setTimeout(function () {
            layer.close(index);
            if (data.elem.checked) {
                layer.msg("置顶成功！");
            } else {
                layer.msg("取消置顶成功！");
            }
        }, 500);
    })

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".btn_search").on("click", function () {
        storePage.getData(1);
//      if($(".searchVal").val() != ''){
//          table.reload("newsListTable",{
//              page: {
//                  curr: 1 //重新从第 1 页开始
//              },
//              where: {
//                  key: $(".searchVal").val()  //搜索的关键字
//              }
//          })
//      }else{
//          layer.msg("请输入搜索的内容");
//      }
    });

    //添加文章
    function addNews(edit) {
        var index = layui.layer.open({
            title: "添加文章",
            type: 2,
            content: "newsAdd.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".newsName").val(edit.newsName);
                    body.find(".abstract").val(edit.abstract);
                    body.find(".thumbImg").attr("src", edit.newsImg);
                    body.find("#news_content").val(edit.content);
                    body.find(".newsStatus select").val(edit.newsStatus);
                    body.find(".openness input[name='openness'][title='" + edit.newsLook + "']").prop("checked", "checked");
                    body.find(".newsTop input[name='newsTop']").prop("checked", edit.newsTop);
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    }

    $(".addNews_btn").click(function () {
        addNews();
    })

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('newsListTable'),
            data = checkStatus.data,
            newsId = [];
        if (data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的文章？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        } else {
            layer.msg("请选择需要删除的文章");
        }
    })

    //列表操作
    table.on('tool(newsList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'edit') { //编辑
            addNews(data);
        } else if (layEvent === 'del') { //删除
            layer.confirm('确定删除此文章？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : data.newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            });
        } else if (layEvent === 'look') { //预览
            layer.alert("此功能需要前台展示，实际开发中传入对应的必要参数进行文章内容页面访问")
        }
    });

})